package com.jd.basic.controller;

import com.jd.basic.utils.AjaxResult;
import com.jd.basic.utils.FastdfsUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 小林同学
 * @version 1.0
 * @description: TODO
 * @date 2023/3/1 12:54
 */
@RestController
@RequestMapping("/fastDfs")
public class FastdfsController {
    @PostMapping
    public AjaxResult upload(@RequestParam(value = "file",required = true ) MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        try {
            String path = FastdfsUtil.upload(file.getBytes(), extension);
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setResultObj("网络错误");
        }
    }
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path",required = true ) String path){

        try {
            String path1 = path.substring(1);
            // 获取组名
            String groupName = path1.substring(0, path1.indexOf("/"));
            // 获取图片途径
            String fileName = path1.substring(path1.indexOf("/") + 1);
            FastdfsUtil.delete(groupName,fileName);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setResultObj("网络错误");
        }

    }

}

